package com.example.tool.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.tool.anno.DictFormat;
import com.example.tool.entity.base.BaseDO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_user")
public class User extends BaseDO implements UserDetails {

    /**
     * 用户id
     */
    @TableId(type = IdType.ASSIGN_ID)
    private String id;
    /**
     * 用户名称
     */
    private String name;

    /**
     * 用户账号
     */

    private String username;

    /**
     *  用户密码
     */
    private String password;

    /**
     * 手机号
     */
    private String phone;

    /**
     * 是否启用
     */
    @DictFormat(value = "user_enable_status",isConvert = true)
    private String isEnable;
    /**
     * 用户性别
     */
    @DictFormat(value = "sex",isConvert = true)
    private String sex; // 0男  1女

    /**
     * 用户权限
     */
    private String roles;


    // 从数据库roles字段转换为List<String>
    public List<String> getRoleList() {
        if (StringUtils.isBlank(roles)) {
            return Collections.emptyList();
        }
        return Arrays.asList(roles.split(","));
    }


    // UserDetails接口实现
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getRoleList().stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
